<?php

namespace App\Http\Controllers\site;

use App\Models\Financial;
use App\Models\Investment;
use App\Models\Order;
use App\Models\User;
use App\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use DB;
use Log;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order as WechatOrder;


class WechatController extends Controller
{
    public function __construct()
    {
        //$this->middleware(['wechat.oauth']);
    }

    //国庆礼包
    public function getGifts(Request $request ,$id=5)
    {
        //
        $app = new Application(config('wechat'));

        $oauth = $app->oauth;
//        echo print_r($oauth); exit();
        // 未登录
        if (empty($_SESSION['wechat_user'])) {
            //$_SESSION['target_url'] = 'user/profile';
            return $oauth->redirect();
        }else{
		    return redirect('wechat/ceshi');
	    }


        $user = Auth::user();
        if($user){
            $item = Financial::where('id', $id)->first();
            $model = Investment::where('financialId',$id)->get();
//            print_r($model); exit;
            return view( 'site.wechat.gifts',[
                'item' =>$item,
                'model' =>$model,
            ]);
        }else{
            return redirect('wechat/login');
        }
    }

    //授权回调
    public function getOauthcallback(Request $request){
        $config = config('wechat');
        $app = new Application($config);
        $oauth = $app->oauth;
        $user = $oauth->user();
        session(['wechat_user' => $user->toArray()]);
        return redirect('wechat/ceshi');
    }

    function getIndex(){
        return view('site.wechat.index',['page'=>'index']);
//        echo '微信首页';
    }

    /**
     * 微信测试
     */
    function  getTest(Request $request){
        $token = 'zhenhaokeji';
        $data = $request->all();
        $signature = $data['signature'];
        $timestamp = $data['timestamp'];
        $nonce = $data['nonce'];
        $echostr = $data['echostr'];
        $arrtep = array($token, $timestamp, $nonce);
        sort($arrtep, SORT_STRING);
        $arrStr = implode($arrtep);
        $hashcode = sha1($arrStr);
        if($hashcode == $signature){
            return $echostr;
        }else{
            return false;
        }
    }

    /**
     * 处理微信请求
     */
    public function serve(){
        Log::info('request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志

        $wechat = app('wechat');
        $wechat->server->setMessageHandler(function($message){
            return "欢迎关注 overtrue！";
        });

        Log::info('return response.');

        return $wechat->server->serve();
    }

    //微信支付测试
    public function getCeshi(Request $request)
    {
        $wechatuser = session('wechat_user');
        $product = [
            'trade_type'       => 'JSAPI', // 微信公众号支付填JSAPI
            'body'             => '一盒火柴',
            'detail'           => '一盒火些',
            'out_trade_no'     => md5(uniqid().microtime()), // 这是自己ERP系统里的订单ID，不重复就行。
            'total_fee'        => 1, // 金额，这里的8888分人民币。单位只能是分。
            'notify_url'       => 'http://hzstkj.cc/wechat/ordernotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid'           => $wechatuser['id'], // 这个不能少，少了要报错。
            // ...  基本上这些参数就够了，或者参考微信文档自行添加删除。
        ];
        $order = new \EasyWeChat\Payment\Order($product);
        $app = new Application(config('wechat'));
        $payment = $app->payment;
        $result = $payment->prepare($order); // 这里的order是上面一步得来的。 这个prepare()帮你计算了校验码，帮你获取了prepareId.省心。
        $prepayId = null;
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id; // 这个很重要。有了这个才能调用支付。
        } else {
            var_dump($result);
            die("出错了。");  // 出错就说出来，不然还能怎样？
        }
        $config = $payment->configForJSSDKPayment($prepayId); // 这个方法是取得js里支付所必须的参数用的。 没这个啥也做不了，除非你自己把js的参数生成一遍
        //$json = $payment->configForPayment($prepayId); // 返回 json 字符串，如果想返回数组，传第二个参数 false
        $js = $app->js;  // 这个是jssdk里页面上需要用到的js参数信息。

        //TODO 根据$config生成本地订单
        //print_r($config); exit();
        return view( 'site.wechat.ceshi',[
            'config' =>$config,
            'js' =>$js,
        ]);
    }

    public  function getOrdernotify(){

    }

    public function getProject($id=36)    #项目贷-衢州项目id=36是衢州项目死的不能修改
    {
        $data=DB::table('financial')->find($id);
//        print_r($data);die();
        return view('site.wechat.project',[
            'data'=> $data,
        ]);
    }
    public function getLogin()  #微信登录
    {
        return view('site.wechat.login');
    }
    public function postLogin(Request $request)
    {
        $data = $request->all();
        $attributes = [
            'name'=>'用户名',
            'password'=>'密码',
            'captcha' =>'验证码'
        ];
        $validator = \Validator::make(
            $data,
            [
                'name' => 'required',
                'password' => 'required',
                'captcha' => 'required|captcha',
            ],
            [
                'required' => ":attribute不能为空",
                'captcha.required' => '请输入验证码',
                'captcha.captcha' => '验证码错误，请重试'
            ],
            $attributes
        );
        if($validator->fails()){
            //判断加入的数据不能为空
            $message = $validator->messages();
            $ret['message'] = $message;
            foreach ($attributes as $k => $attr) {
                if ($message->has($k)) {
                    return back()->with('msg', $message->first($k));
                }
            }
        }elseif(Auth::attempt(['name'=>$request['name'], 'password'=>$request['password']], true)){
            return redirect('/wechat/gifts');
        }else{
            return back()->with('msg','用户名或密码错误');
        }
    }


    public function getRegister()
    {
        return view('site.wechat.register');
    }
    /**
     * 发送手机验证码
     */
    public function postValidatecode(Request $request){
        $data = $request->all();
        $code = rand(1000, 9999);
        session([config('session.session_key.register')=>$code]);
        $content = "您好，您本次注册的验证码是" . $code . '，请妥善保管。';
        $result = sendsms($data['mobile'], $content);
        return \Response::json($result);
    }

    public function postRegister(Request $request)//  这是注册的方法
    {
        $data = $request->all();
        $attributes = [
            'name'=>'用户名',
            'password'=>'密码',
            'password_confirmation'=>'确认密码',
            'mobile'=>'手机号',
            'idNo'=>'身份证号',
            'validateCode'=>'验证码',
        ];
        $rules = [
            'name'=>'required|unique:users',
            'password' => array('bail', 'required', 'confirmed', 'regex:/^\w{6,15}$/'),
            'password_confirmation' => 'required',
            'mobile' => array('required','regex:/^1[3|4|5|6|7|8|9]\d{9}$/', 'unique:users'),
            'validateCode'=>array('required', 'validatesmsg:register'),
            'idNo'=> array('required','regex:/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X|x)$/i'),
            'agree' => 'required',
        ];
        $messages = [
            'required'=>':attribute不能为空',
            'password.regex'=>'密码是6至15位数字，字母，下划线',
            'regex'=>':attribute格式不正确',
            'name.unique'=>'用户名已被注册',
            'mobile.unique'=>'手机号已经被注册',
            'password.confirmed'=>'两次输入的密码不一致',
            'validateCode.validatesmsg'=>'验证码不正确',
            'agree.required'=>'请选择注册协议'
        ];
        $validator = Validator::make($data, $rules, $messages,$attributes);
        if ($validator->fails()) {
            $request->flash();
            return back()->withErrors($validator);
        }
        $data = [
            'name' =>$data['name'],
            'password' =>bcrypt($data['password']),
            'mobile' =>$data['mobile'],
            'idNo' =>$data['idNo'],
        ];
        $role = Role::where('name','user')->first();
        $user = User::findOrNew(0);
        $user->fill($data);
        DB::transaction(function() use($user,$role){
            $user->save();
            $user->attachRole($role);
        });
        return redirect('wechat/gifts');
    }

    /**
     * 购买，生成订单
    */
    public function getBuy(Request $request, $fid){
        $user = Auth::user();
        if($user){
            $order = Order::findOrNew(0);
            $data = [
                'financialId'   => $fid,
                'userId'         => $user->id,
                'number'         => 1,
                'status'         => 0,
                'obonus'         => 0,
                'source'         => 2,
            ];
            $order->fill($data);
            $order->save();
            $item = Financial::where('id', $fid)->first();
            return view( 'site.wechat.buy',[
                'item' =>$item,
            ]);
        }else{
            return redirect('wechat/login');
        }
    }
    public function getProduct()
    {
        return view('site.wechat.product');
    }
    public function postPayment()
    {
        $product = [
            'body'             => '一盒火柴',
            'trade_type'       => 'JSAPI',
            'out_trade_no'     => 'ERP'.time(),
            'total_fee'        => 1,
            'notify_url'       => 'http://test.xxoo.com/wechat/notify/',
            'openid'           => $_SESSION['openid'],
            'attach'           => '卖火柴的小女孩',
        ];

        $order = new Order($product);

        $app = new Application(config('wechat'));
        $js = $app->js;
        $payment = $app->payment;
        $result = $payment->prepare($order);
        $prepayId = null;
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
        } else {
            var_dump($result);
            die("出错了。");
        }
        $config = $payment->configForJSSDKPayment($prepayId);
    }

    public function getMyinformation($id=0)
    {
        $user = Auth::user();

        return view('site.wechat.myinformation',[
            'user' => $user,

        ]);
        //echo "个人信息";
    }
    public function postMyinformation(Request $request,$id=0) #个人信息提交数据
    {
        $model = User::findOrNew($id);
//        print_r($model);exit;
        $data = $request->all();
        unset($data['_token']);
        unset($data['_token']);
        $attributes = [
            'nickName'=>'姓名',
            'mobile'=>'手机号码',
            'email'=>'邮箱',
            'adderss' => '居住地',
        ];
        $validator = \Validator::make(
            $data,
            [
                'nickName' => 'required',
                'mobile' => 'required',
                'email' => 'required',
                'adderss' => 'required',
            ],
            [
                'required' => ":attribute不能为空",
            ],
            $attributes
        );
        if($validator->fails()){
            //判断加入的数据不能为空
            $message = $validator->messages();
            $ret['message'] = $message;
            foreach ($attributes as $k => $attr) {
                if ($message->has($k)) {
                    $ret['state'] = 'fail';
                    $ret['message'] = $message->first($k);
                    break;
                }
            }

        }else{
            $model->fill($data);
            $model->save();//写入数据库
            if($model && $model->id>0){
                $ret = ['state' => 'success', 'message' => '操作成功'];
            }else{
                $ret = ['state' => 'fail', 'message' => '操作失败'];
            }
        }
        return \Response::json($ret);
    }
    public function getPersonal()
    {
       return view('site.wechat.personal');
    }
    public function getOrder()
    {
        return view('site.wechat.order');
    }
    public function getInvestmentway()
    {
        return view('site.wechat.investmentway');
    }

}
